<template>
  <nut-tabs v-model="activeTab" class="reservation-order-container p-4 bg-gray-100 min-h-screen">
    <nut-tabpane title="预约订单">
      <div v-if="loadingOrders" class="text-center text-gray-500 mt-10">加载中...</div>
      <div v-else-if="orders.length === 0" class="text-center text-gray-500 mt-10">暂无历史订单</div>
      <ul v-else class="space-y-4" style="padding: 0px">
        <li v-for="order in orders" :key="order.id" class="bg-white rounded-lg shadow overflow-hidden">
          <div class="p-4">
            <div class="flex justify-between items-start text-sm mb-3">
              <div class="flex-1 mr-4">
                <p class="text-gray-500">订单号：</p>
                <p class="font-medium text-gray-800 break-all">{{ order.businessOrderId }}</p>
              </div>
              <div class="text-right flex-shrink-0">
                <p class="text-gray-500">预约时间：</p>
                <p class="font-medium text-gray-800 whitespace-nowrap">{{ formatDate(order.orderTime) }}</p>
              </div>
            </div>
            <div class="border-t border-gray-200 pt-3 mb-3">
              <p class="text-gray-600 mb-1">
                服务名称：<span class="text-gray-800 font-medium">{{ order.remarks }}</span>
              </p>
              <p class="text-gray-600 mb-1">
                服务类型：<span class="text-gray-800 font-medium">{{ getServiceName(order.serviceId) }}</span>
              </p>
              <p class="text-gray-600 mb-1">
                服务人员：<span class="text-gray-800 font-medium">{{
                  getServicePersonName(order.servicePersonId)
                }}</span>
              </p>
              <p class="text-gray-600">
                订单状态：
                <span :class="getStatusClass(order.orderStatus)" class="font-semibold">{{ order.orderStatus }}</span>
              </p>
            </div>
          </div>
          <div class="order-actions bg-gray-50 px-4 py-3 flex justify-end space-x-2">
            <button
              @click="viewOrderDetails(order.businessOrderId)"
              class="px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600 text-sm shadow-sm"
            >
              查看详情
            </button>
            <template v-if="usertype === 'service'">
              <template v-if="order.orderStatus === '待服务' || order.orderStatus === '已预约'">
                <button
                  v-if="order.orderStatus === '待服务'"
                  @click="startService(order.businessOrderId)"
                  class="px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600 text-sm shadow-sm"
                >
                  开始服务
                </button>
                <button
                  @click="cancelorder(order.businessOrderId)"
                  class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 text-sm shadow-sm"
                >
                  取消订单
                </button>
              </template>
              <template v-else-if="order.orderStatus === '进行中'">
                <button
                  @click="finishService(order.businessOrderId)"
                  class="px-3 py-1 bg-yellow-500 text-white rounded hover:bg-yellow-600 text-sm shadow-sm"
                >
                  完成服务
                </button>
              </template>
            </template>
            <template v-else-if="usertype === 'customer' && order.orderStatus === '已完成'">
              <button
                @click="evaluateOrder(order.businessOrderId)"
                class="px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600 text-sm shadow-sm"
              >
                立即评价
              </button>
              <button
                @click="complainOrder(order.businessOrderId)"
                class="px-3 py-1 bg-yellow-500 text-white rounded hover:bg-yellow-600 text-sm shadow-sm"
              >
                想要投诉
              </button>
            </template>
          </div>
        </li>
      </ul>
    </nut-tabpane>
    <nut-tabpane v-if="usertype === 'customer'" title="全部需求">
      <div v-if="loadingDemands" class="text-center text-gray-500 mt-10">加载中...</div>
      <div v-else-if="demands.length === 0" class="text-center text-gray-500 mt-10">暂无需求记录</div>
      <ul v-else class="space-y-4" style="padding: 0px">
        <li v-for="item in demands" :key="item.businessOrderId" class="bg-white rounded-lg shadow overflow-hidden">
          <div class="p-4">
            <div class="flex justify-between items-start text-sm mb-3">
              <div class="flex-1 mr-4">
                <p class="text-gray-500">需求编号：</p>
                <p class="font-medium text-gray-800 break-all">{{ item.id }}</p>
              </div>
              <div class="text-right flex-shrink-0">
                <p class="text-gray-500">发布时间：</p>
                <p class="font-medium text-gray-800 whitespace-nowrap">{{ formatDate(item.publishTime) }}</p>
              </div>
            </div>
            <div class="border-t border-gray-200 pt-3 mb-3">
              <p class="text-gray-600 mb-1">
                需求描述：<span class="text-gray-800 font-medium">{{ item.description }}</span>
              </p>
              <p class="text-gray-600 mb-1">
                预约时间：<span class="text-gray-800 font-medium">{{ item.serviceStartTime }}</span>
              </p>
              <p class="text-gray-600 mb-1">
                位置：<span class="text-gray-800 font-medium">{{ item.location }}</span>
              </p>
              <p class="text-gray-600 mb-1">
                服务类型：<span class="text-gray-800 font-medium">{{ item.type }}</span>
              </p>
              <p class="text-gray-600">
                状态：
                <span :class="getStatusClass(item.status)" class="font-semibold">{{ item.status }}</span>
              </p>
            </div>
          </div>
          <div class="demand-actions bg-gray-50 px-4 py-3">
            <button
              v-if="item.status === '待接单' || item.status === '已取消' || item.status === '已完成'"
              @click="deleteDemand(item.id)"
              class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 text-sm shadow-sm block ml-auto"
            >
              删除需求
            </button>
            <button
              v-if="item.status === '已完成'"
              @click="evaluateOrder(order.businessOrderId)"
              class="px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600 text-sm shadow-sm"
            >
              立即评价
            </button>
            <button
              v-if="item.status === '已完成'"
              @click="complainOrder(order.businessOrderId)"
              class="px-3 py-1 bg-yellow-500 text-white rounded hover:bg-yellow-600 text-sm shadow-sm"
            >
              想要投诉
            </button>
          </div>
        </li>
      </ul>
    </nut-tabpane>
  </nut-tabs>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getCustomerOrders, getCustomerDemand, cancelOrder, deletedemand } from "@/api/customer";
import { getServicePersonOrders, startservice, finishservice } from "@/api/service";
import { uerPersonStore } from "@/store/modules/person";

const { getServerType, getserverperson } = uerPersonStore();

const userId = uni.getStorageSync("userId");
const activeTab = ref(0);
const usertype = ref(uni.getStorageSync("usertype"));

// 订单相关
const loadingOrders = ref(true);
const orders = ref([]);
const demand = ref([]);
const services = ref([]);
const servicePersonnel = ref([]);

// 需求相关
const loadingDemands = ref(false);
const demands = demand;

//根据 serviceId 从 services 数组获取服务类型名称
const getServiceName = (serviceId) => {
  const service = services.value.find((s) => s.id === serviceId);
  return service ? service.name : `未知服务 (ID: ${serviceId})`;
};

//根据 servicePersonId 从 servicePersonnel 数组获取服务人员姓名
const getServicePersonName = (servicePersonId) => {
  if (servicePersonId === null || servicePersonId === undefined) {
    return "待分配";
  }
  const person = servicePersonnel.value.find((p) => p.id === servicePersonId);
  return person ? person.name : `未知人员 (ID: ${servicePersonId})`;
};

// 获取订单状态对应的 CSS 类名
const getStatusClass = (status) => {
  switch (status) {
    case "待服务":
      return "text-orange-500";
    case "已完成":
      return "text-green-500";
    case "已取消":
    case "被投诉":
      return "text-red-500";
    case "进行中":
    case "待审核":
      return "text-yellow-500";
    case "已预约":
      return "text-blue-500";
    default:
      return "text-gray-500";
  }
};

// 查看订单详情
const viewOrderDetails = (orderId) => {
  console.log("查看订单详情:", orderId);
  uni.navigateTo({
    url: `/pages/modules/user/myself/OrderDetail/index?id=${orderId}`,
  });
};
//开始服务
const startService = async (orderId) => {
  uni.showModal({
    title: "确认开始服务",
    content: "确定要开始服务吗？",
    success: async (res) => {
      if (res.confirm) {
        try {
          await startservice(orderId);
          uni.showToast({ title: "开始服务成功", icon: "success" });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } catch (error) {
          console.error("开始服务失败:", error);
          uni.showToast({ title: "开始服务失败", icon: "none" });
        }
      }
    },
  });
};
//完成服务
const finishService = async (orderId) => {
  uni.showModal({
    title: "确认完成服务",
    content: "确定完成服务了吗？",
    success: async (res) => {
      if (res.confirm) {
        try {
          await finishservice(orderId);
          uni.showToast({ title: "完成服务成功", icon: "success" });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } catch (error) {
          console.error("完成服务失败:", error);
          uni.showToast({ title: "完成服务失败", icon: "none" });
        }
      }
    },
  });
};

//取消订单
const cancelorder = async (orderId) => {
  uni.showModal({
    title: "确认取消",
    content: "确定要取消该订单吗？",
    success: async (res) => {
      if (res.confirm) {
        try {
          await cancelOrder(orderId);
          uni.showToast({ title: "取消订单成功", icon: "success" });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } catch (error) {
          console.error("取消订单失败:", error);
          uni.showToast({ title: "取消订单失败", icon: "none" });
        }
      }
    },
  });
};

// 立即评价
const evaluateOrder = (orderId) => {
  uni.navigateTo({
    url: `/pages/modules/user/myself/Evaluate/index?id=${orderId}`,
  });
};

// 想要投诉
const complainOrder = (orderId) => {
  uni.navigateTo({
    url: `/pages/modules/user/myself/Complain/index?id=${orderId}`,
  });
};
//删除需求
const deleteDemand = async (demandId) => {
  uni.showModal({
    title: "确认取消",
    content: "确定要取消该订单吗？",
    success: async (res) => {
      if (res.confirm) {
        try {
          await deletedemand({ demandId });
          uni.showToast({ title: "删除成功", icon: "success" });
          await fetchDemands();
        } catch (error) {
          console.error("删除需求失败:", error);
          uni.showToast({ title: "删除失败", icon: "none" });
        }
      }
    },
  });
};

// --- 生命周期钩子 ---
onMounted(() => {
  init();
});
//初始化
const init = async () => {
  loadingOrders.value = true;
  loadingDemands.value = true;
  try {
    if (usertype.value === "customer") {
      await Promise.all([fetchOrders(), fetchServices(), fetchServicePersonnel(), fetchDemands()]);
    } else {
      await Promise.all([fetchOrders(), fetchServices(), fetchServicePersonnel()]);
    }
  } catch (error) {
    console.error("页面初始化加载数据失败:", error);
  } finally {
    loadingOrders.value = false;
    loadingDemands.value = false;
  }
};

// 调用获取历史订单
const fetchOrders = async () => {
  try {
    let response;
    if (usertype.value === "customer") {
      response = await getCustomerOrders(userId);
    } else {
      response = await getServicePersonOrders(userId);
    }
    orders.value = response.data;
    console.log("获取历史订单成功:", orders.value);
  } catch (error) {
    console.error("获取历史订单失败:", error);
    throw error;
  }
};
//获取历史需求
const fetchDemands = async () => {
  try {
    const response = await getCustomerDemand(userId);
    demand.value = response.data;
    console.log("获取需求列表成功:", demand.value);
  } catch (error) {
    console.error("获取需求列表失败:", error);
  }
};

// 获取服务列表函数
const fetchServices = async () => {
  try {
    // 调用 store 中的方法获取服务类型数据
    const allServicesData = await getServerType();

    // 检查返回的数据是否有效且为数组
    if (Array.isArray(allServicesData)) {
      // 使用 map 提取 id 和 name
      services.value = allServicesData.map((service) => ({
        id: service.id,
        name: service.name,
      }));
      console.log("获取并处理服务列表成功:", services.value);
    } else {
      console.warn("getServerType 未返回有效的数组数据:", allServicesData);
      services.value = []; // 或者设置一个默认的空数组
    }
  } catch (error) {
    console.error("获取服务列表失败:", error);
    services.value = []; // 发生错误时也设置为空数组
    // Throw error to be caught by Promise.all
    throw error;
  }
};

// 获取服务人员列表函数
const fetchServicePersonnel = async () => {
  try {
    // 调用 store 中的方法获取服务人员数据
    const allPersonnelData = await getserverperson();

    // 检查返回的数据是否有效且为数组
    if (Array.isArray(allPersonnelData)) {
      // 使用 map 提取 id 和 name
      servicePersonnel.value = allPersonnelData.map((person) => ({
        id: person.id,
        // 假设服务人员对象也有 'name' 属性，如果不是请调整
        name: person.name,
      }));
      console.log("获取并处理服务人员列表成功:", servicePersonnel.value);
    } else {
      console.warn("getserverperson 未返回有效的数组数据:", allPersonnelData);
      servicePersonnel.value = []; // 或者设置一个默认的空数组
    }
  } catch (error) {
    console.error("获取服务人员列表失败:", error);
    servicePersonnel.value = []; // 发生错误时也设置为空数组
    // Throw error to be caught by Promise.all
    throw error;
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return "";
  try {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")} ${hours}:${minutes}`;
  } catch (error) {
    console.error("Error formatting date:", dateString, error);
    return dateString;
  }
};
</script>

<style lang="scss" scoped></style>
